/**
 * Created by lenovo on 2017/5/3.
 */
var browserType;
var timer;
(function () {
  timer = setInterval('getresult()',500);






})()
function getresult(){
    clearInterval(timer);
    /**
     * 判断浏览器是否是微信浏览器
     * @returns {boolean}
     */
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i) == 'micromessenger'){
        browserType=true;
    }else{
        browserType=false;
    }
    $.ajax({
        url: wxUrl,
        data: {'url':  window.location.href},
        type: "get",
        success: function (data) {
            //console.info(data);
           // debugger;
            if(data.data)
            {
            }
            else
            {
                var data=JSON.parse(data);
            }

            var noncestr = data.data.nonceStr;
            var timestamp = data.data.timestamp;
            var signature = data.data.signature;
            scanCode(noncestr, timestamp, signature);
        }
    });
    var scanCode = function (str, timestamp, signature) {
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId:appId, // 必填，企业号的唯一标识，此处填写企业号corpid
            timestamp: timestamp, // 必填，生成签名的时间戳
            nonceStr: str, // 必填，生成签名的随机串
            signature: signature,// 必填，签名，见附录1
            jsApiList: [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                'onMenuShareQZone',
                'startRecord',
                'stopRecord',
                'onVoiceRecordEnd',
                'playVoice',
                'pauseVoice',
                'stopVoice',
                'onVoicePlayEnd',
                'uploadVoice',
                'downloadVoice',
                'chooseImage',
                'previewImage',
                'uploadImage',
                'downloadImage',
                'translateVoice',
                'getNetworkType',
                'openLocation',
                'getLocation',
                'hideOptionMenu',
                'showOptionMenu',
                'hideMenuItems',
                'showMenuItems',
                'hideAllNonBaseMenuItem',
                'showAllNonBaseMenuItem',
                'closeWindow',
                'scanQRCode',
                'chooseWXPay',
                'openProductSpecificView',
                'addCard',
                'chooseCard',
                'openCard',
                'chooseVideo',
                'uploadVideo',
                'onVideoUploadProgress'
            ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });

        wx.ready(function () {
        });
        wx.error(function(){

        })
    }
}

var serverId = new Map();
var vidoId=new Map();
var viewId=new Map();
var shipId;
var localimgId = new Map();
var localIds = new Array();
var num = 0;
var biaos=0;
var picId = new Map();
/**
 * 选取图片(拍照或从手机相册中选图接口)
 */
function chooseImg(mark) {
    if(!browserType){
       /* $("#pic").html("<form id='uploadform_' method='POST' enctype='multipart/form-data'>" +
            "<input class='weui_uploader_input_new ' name='uploadfile' style='display:none;;' id='upload_' type='file'  accept='image/jpg,image/jpeg,image/png,image/gif' multiple=''/>" +
            "<canvas id='myCanvas0' style='display: none' ></canvas><img src='' alt='' id='ago0' style='display: none;'/>"+
            "</form>");
        $('#upload_').bind("change",function(e){
            file.upload(e);
            biaos=mark;
        });
        $('#upload_').click();*/
    }else{
    if(num>=3){
        alert("最多上传3张图片！");
        return ;
    }
    var count=3-parseInt(num);
    wx.chooseImage({
        count: count, // 默认9
        sizeType: [ 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
            if(num>3){
                alert("最多上传3张图片！");
                return ;
            }
            num+=res.localIds.length;
            localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
            var localid=new Array();
            if(localimgId.get("localPicId")==null||localimgId.get("localPicId")==undefined||localimgId.get("localPicId")==""){

            }else{
                localid=localimgId.get("localPicId");
            }
            localimgId.put("localPicId",localid.concat(localIds))
            localImg(mark);
        }
    });
    }
}
/**
 * 上传图片
 */
function localImg(mark) {
    var localid = localIds.pop();
    wx.uploadImage({
        localId: localid,
        isShowProgressTips: 2, // 默认为1，显示进度提示
        success: function (res) {
            picId.put(localid,res.serverId);
            if (localIds.length > 0) {
                localImg(mark);
            }else{
                showImage();
            }
        },
        fail: function (res) {
            alert(JSON.stringify(res));
        }
    });
}

/**
 * 上传到后台
 * @param serviceId
 * @param localid
 * @param mark
 */
function uploadImg(serviceId,localid,mark){//mark:  0-图片  1:视屏 2：语音
    var url;
    url=uploadUrl+"api/danger/content/uploadimg/"+serviceId+"/"+mark;

    $.ajax({
        url: url ,
        type: "get",
        dataType: "json",
        success: function (resp) {
            if (resp && resp.succ) {
                serverId.put(localid,resp.data);
               // console.info(serverId);
                if (localIds.length > 0) {
                    localImg(mark);
                }else{
                    showImage();
                }
            }
        }
    });
}
/**
 * 展示图片
 */
function showImage() {
    var localimg=localimgId.get("localPicId");
    $('#picshow').empty();
    $.each(localimg, function (i, n) {
       // $('#picshow').append("<div class='img1' style='margin-bottom: 10px;margin-right: 15px;float:left;' ><img src='" + n + "' onclick='showAutoImg(\"" + n + "\")' width='80px' height='80px'/><div class='sxsb_close' onclick='revokeImg(this,\""+n+"\");'></div></div>");
        $('#picshow').append("<p><img src='" + n + "' onclick='showAutoImg(\"" + n + "\")'><i class='icon-close' onclick='revokeImg(this,\""+n+"\");'></i></p>");
    });
}
/**
 * 图片预览
 * @param obj
 */
function showAutoImg(obj) {
    //debugger;
    $.showPic(obj);
}
/**
 * 删除图片
 * @param obj
 * @param n
 */
function revokeImg(obj,n) {
    num-=1;
    $(obj).parent("p").remove();
    var imgkey =  n;
    picId.keys==prototyperemove(picId.keys,imgkey);
    picId.data=prototyperemove(picId.data,imgkey);
    if(browserType){
    var localimg = new Array();
    localimg = localimgId.get("localPicId");
    localimg = prototyperemove(localimg, imgkey);
    localimgId.put("localPicId", localimg);}
}
/**
 *  app上传图片
 * @param files
 */
function appUpload(files,mark){
    if (files.length > 3 || $("#img_>.img1").length >= 3) {
        alert("上传的图片不得多于3张");
        return;
    }
    var num1 = files.length;
    var num2 = document.getElementById('picshow').children.length;
    if (num1 + num2 > 3) {
        alert("上传的图片不得多于3张");
        return;
    }else{
        lockBtn();
        lockBg();
        //debugger;
    var Cnv = document.getElementById('myCanvas0');
    var Cntx = Cnv.getContext('2d');//获取2d编辑容器
    var imgss =   new Image();
    var agoimg=document.getElementById("ago0");
    for (var intI = 0; intI < files.length; intI++) {
        var tmpFile = files[intI];
        var reader = new FileReader();
        reader.readAsDataURL(tmpFile);
        reader.onload = function (e) {
            //alert("a");
            url = e.target.result;
            //console.log(url.length);
            imgss.src = url;
            agoimg.src=url;
            agoimg.onload = function () {

                Cnv.height =imgss.height;
                Cnv.width= imgss.width ;
                Cntx.drawImage(agoimg, 0, 0,imgss.width,imgss.height);
                var Pic = document.getElementById("myCanvas0").toDataURL("image/png");
                //alert("1++++"+Pic.length);
                var maxSize = 2000000;//4M
                if(Pic.length>=maxSize)
                {
                    // alert(2);
                    //等比缩放
                    var m = maxSize /Pic.length;
                    // alert(m);
                    Cnv.height =imgss.height*m;//该值影响缩放后图片的大小
                    Cnv.width= imgss.width*m ;
                    //img放入画布中
                    //设置起始坐标，结束坐标
                    Cntx.drawImage(agoimg, 0, 0, Cnv.width,Cnv.height);
                    // alert(4);
                }
                var Pic = document.getElementById("myCanvas0").toDataURL("image/png");
                //alert("2+++"+Pic.length);
                if(Pic==null||Pic==""){
                    alert("请重新选择图片!");
                    return;

                }
                Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "");
                // alert("3++++"+Pic.length);
                if(mark==2){
                    url= uploadUrl+"api/uploadPic/appUploadFZImg";
                }else{
                    url=uploadUrl+"api/uploadPic/appUploadImg";
                }
                $.ajax({
                    url:url,
                    async:false,
                    type : 'POST',
                    dataType : 'json',
                    data:{
                        "base64" :Pic,
                    },
                    beforeSend: function () {

                    },
                    success: function (resp, status, xhr) {
                        appImage(tmpFile,resp.data);
                    }, complete: function (XMLHttpRequest, status) {
                        unlockBg();
                        unlockBtn();
                    }
                });

            }
        }
    }
    }
}

var mark1;
var mark2;
var file = {
    upload: function (e) {
        var self = this;
        var files = e.target.files;
        if(files.length>0){
            if (files.length > 3 || $("#picshow>.img1").length >= 3) {
                alert("上传的图片不得多于3张");
                return;
            }
            var num1 = files.length;
            var num2 = document.getElementById('picshow').children.length;
            if (num1 + num2 >3) {
                alert("上传的图片不得多于3张");
                return;
            }else {
                mark1=files.length;
                mark2=0;
                //debugger;
                lockBtn();
                lockBg();
                //alert(123);
                for (var i = 0; i < files.length; i++) {
                    var reader = new FileReader();
                    reader.readAsDataURL(files[i]);
                    reader.onloadstart = function () {
                        //用以在上传前加入一些事件或效果，如载入中...的动画效果
                    };
                    reader.onloadend = function (e) {
                        var dataURL = this.result;
                        var imaged = new Image();
                        imaged.src = dataURL;
                        imaged.onload = function () {  //利用canvas对图片进行压缩
                            var canvas = document.createElement('canvas');
                            var ctx = canvas.getContext('2d');
                            var w = 0;
                            var h = 0;
                            var maxSize=2000000;
                            //debugger;
                            if(dataURL.length>maxSize){
                                var m = maxSize /dataURL.length;
                                w=this.width*m;
                                h=this.height*m;
                            }else{
                                w=this.width;
                                h=this.height;
                            }
                           /* if (this.width > this.height) {
                                h = 1000;
                                var scale = this.width / this.height;
                                h = h > this.height ? this.height : h;
                                w = h * scale;
                            }
                            else {
                                w = 1000;
                                var scale = this.width / this.height;
                                w = w > this.width ? this.width : w
                                h = w / scale;
                            }*/
                            var anw = document.createAttribute("width");
                            var anh = document.createAttribute("height");
                           /* if (this.width > this.height) {
                                anw.value = h;
                                anh.value = w;
                            }
                            else {
                                anw.value = w;
                                anh.value = h;
                            }*/
                            anw.value=w;
                            anh.value=h;
                            canvas.setAttributeNode(anw);
                            canvas.setAttributeNode(anh);
                           /* if (this.width > this.height) {*!/
                                ctx.translate(h, 0);
                                ctx.rotate(90 * Math.PI / 180)
                                ctx.drawImage(this, 0, 0, w, h);
                                ctx.restore();
                            }
                            else {*/
                                ctx.drawImage(this, 0, 0, w, h);
                           /* }*/
                            dataURL = canvas.toDataURL('image/jpg');
                            //回调函数用以向数据库提交数据
                            self.callback(dataURL);
                        };
                    };

                }
            }
        }
    },
    callback: function (dataURL) {
        var Pic = dataURL;
        //alert("2+++"+Pic.length);
        if(Pic==null||Pic==""){
            alert("请重新选择图片!");
            return;

        }
        Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "");
        // alert("3++++"+Pic.length);
        /*if(biaos==2){
            url= uploadUrl+"api/uploadPic/appUploadFZImg";
        }else{
            url="http://localhost/szgawx/"+"api/uploadPic/appUploadImg";
        }*/
        url=uploadUrl+"api/uploadPic/appUploadFZImg";
        $.ajax({
            url:url,
            async:true,
            type : 'POST',
            dataType : 'json',
            data:{
                "base64" :Pic,
            },
            beforeSend: function () {
              /*  lockBtn();
                lockBg();*/
            },
            success: function (resp, status, xhr) {
                if(resp.data!=null){
                    appImage(dataURL,resp.data);
                }else{
                    alert("图片上传失败，请重新上传");
                }


            }, complete: function (XMLHttpRequest, status) {

            }
        });
    },
}









function appImage(src,data){
   /* var src = null;
    if (window.createObjectURL != undefined) {
        src = window.createObjectURL(file);
    } else if (window.URL != undefined) {
        src = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) {
        src = window.webkitURL.createObjectURL(file);
    }*/
    $('#picshow').append("<div class='img1' style='margin-bottom: 10px;' ><img src='" + src + "' onclick='showAutoImg(\"" + src + "\")' width='60px' height='60px'/><div class='sxsb_close' onclick='revokeImg(this,\""+src+"\");'></div></div>");
    serverId.put(src,data);
    mark2+=1;
    if(mark2==mark1){
        unlockBg();
        unlockBtn();
    }

}
